package com.geek.javase.ch17.work.tcpwork.tcp2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/*
 *@Date 2025/11/4
 *@Author wangpeng
 *@Description
 * 需求2：服务端接收多条消息，客户端发送多条消息
 */
public class TCPServer {
    public static void main(String[] args) {
        System.out.println("-------服务器--------");
        ServerSocket ss = null;
        Socket s = null;
        BufferedReader br = null;

        try{
            //1.创建服务器
            ss = new ServerSocket(8899);
            //2.接收客户端
            s = ss.accept();
            System.out.println("客户端已成功接入！");
            //3.服务端读消息
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //循环读消息
            String str = null;
            while ((str = br.readLine()) != null) {
                System.out.println("客户端说：" + str);
                if (str.equals("exit")){
                    break;
                }

            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            //关闭连接、流
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(s!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(br!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
